import React, { useEffect, useState, useContext } from "react";
import {
  ActivityIndicator,
  Image,
  TouchableHighlight,
  TouchableOpacity,
  View,
} from "react-native";
import { MessageType, ChatMessage } from "@/types/chat-message";
import styles from "./index.style";
import AutoSizeImage from "./AutoSizeImage";
import LinkText from "@/components/Global/LinkText";
import { MessageStatus } from "@/types/chat-message";
import AutoSizeVideo from "./AutoSizeVideo";
import { router } from "expo-router";
import { toQueryString } from "@/utils/url-utils";
import { RadioButton } from "react-native-paper";
import ReplyContent from "@/components/Chat/ChatDetail/MessageItem/ReplyContent";
import VoiceMessage from "@/components/Chat/ChatDetail/MessageItem/VoiceMessage";
import MenuTrigger from "./HorizontalMenuTrigger";
import Clipboard from "@react-native-clipboard/clipboard";
import { SourceType } from "@/types/contact";
import CurrentUserIdManager from "@/utils/user-utils";
import {
  useChatMessageActions,
  useChatMessageState,
} from "@/hooks/chat/chat-message";
import { MaterialIcons } from "@expo/vector-icons";
import { useStompSend } from "@/hooks/stomp/stomp-send";
import { ChatDetailContext } from "@/components/Chat/ChatDetail";
import AnimationEmoji from "@/components/Chat/ChatDetail/MessageItem/AnimationEmoji";
import { MenuView, MenuComponentRef } from '@react-native-menu/menu';

/**
 * MessageItem 组件 消息列表项
 * 支持长按菜单操作、多选、转发、引用等功能
 *
 * @author BelovedLYC
 */
const MessageItem: React.FC<{
  item: ChatMessage<any, any>;
}> = ({ item }) => {
  const [showMenu, setShowMenu] = useState(false);
  const { sessionType } = useContext(ChatDetailContext);
  const { selectedMessages, enableMultipleSelect} = useChatMessageState();
  const { addSelectedMessage } = useChatMessageActions();
  const isCurrentUser = item.user.id === CurrentUserIdManager.getUserId();
  const { sendChatMessage } = useStompSend();

  // 对于正在处于发送状态的消息，是否给予警告状态
  const [showWarning, setShowWarning] = useState(false);

  // 根据消息类型决定菜单项
  const getMenuItems = () => {
    const baseMenuItems = ["复制", "转发", "回复"];
    // 只有自己发送的消息才能删除
    if (isCurrentUser) {
      baseMenuItems.push("删除");
    }
    return baseMenuItems;
  };

  // 处理菜单项点击
  const handleMenuItemPress = (menuItem: string) => {
    switch (menuItem) {
      case "复制":
        if (item.messageType === MessageType.TEXT) {
          const textPayload =
            typeof item.content === "string"
              ? JSON.parse(item.content)
              : item.content;
          Clipboard.setString(textPayload.text);
          console.log("已复制文本内容:", textPayload.text);
        }
        break;
      case "转发":
        break;
      case "回复":
        break;
      case "删除":
        break;
    }
  };

  // 处理引用消息的载荷
  const prepareQuotePayload = () => {
    if (!item.reply) return null;

    try {
      if (typeof item.reply.replyContent === "string") {
        return JSON.parse(item.reply.replyContent);
      }
      return item.reply.replyContent;
    } catch (e) {
      console.log("解析引用消息载荷失败:", e);
      return item.reply.replyContent;
    }
  };

  // 处理消息内容渲染
  const Information = () => {
    item.content = typeof item.content === "string"
            ? (JSON.parse(item.content))
            : (item.content);
    switch (item.messageType) {
      case MessageType.TEXT:
        return <LinkText content={item.content.text} />;
      case MessageType.IMAGE:
        return (
          <AutoSizeImage
            uri={item.content.url}
            messageId={item.messageId}
            setShow={() => {}}
          />
        );
      case MessageType.VIDEO:
        return (
          <AutoSizeVideo
            uri={item.content.url}
            thumbnail={item.content.thumbnail}
            messageId={item.messageId}
            setShow={() => {}}
          />
        );
      case MessageType.VOICE:
        return (
          <VoiceMessage
            audioSource={item.content.url}
            isCurrentUser={isCurrentUser}
            setShow={() => {}}
          />
        );
      case MessageType.FILE:
        return (<></>)
      case MessageType.EMOJI:
        return (
            <AnimationEmoji  uri={item.content.url}
                             messageId={item.messageId}
                             setShow={() => {}}/>
        )
    }
  };

  const onTouchAvatarPress = (senderId: string) => {
    // 路由到用户页面
    router.navigate(
      `userprofile/${senderId}?${toQueryString({
        type: SourceType.ID,
      })}`
    );
  };

  useEffect(() => {
    let timeout: NodeJS.Timeout | undefined;
    if (item.status === MessageStatus.SENDING) {
      timeout = setTimeout(() => {
        setShowWarning(true);
      }, 3000);
    } else {
      // 如果不是 SENDING，就清除警告
      setShowWarning(false);
    }

    return () => {
      if (timeout) clearTimeout(timeout);
    };
  }, [item.status]); // 每条消息单独监听

  // 处理重试发送消息
  const handleRetry = () => {
    sendChatMessage({ ...item, sessionType });
  };

  // 处理消息点击（多选模式下可以选择消息）
  const handleMessagePress = () => {
    if (enableMultipleSelect) {
      addSelectedMessage(item.messageId);
    }
  };

  // 判断消息是否有引用内容
  const hasQuote = !!item.reply && !!item.reply.replyMessageId;
  const quotePayload = hasQuote ? prepareQuotePayload() : null;

  // 确保引用消息始终有正确显示内容
  const ensureQuoteContent = () => {
    // 如果没有引用消息，直接返回
    if (!hasQuote) return false;

    // 有引用ID和发送者名称，但可能没有内容
    if (!quotePayload && typeof item.reply.replyContent === "string") {
      console.log("尝试解析引用内容:", item.reply.replyContent);
      return true; // 即使没有解析成功，也显示引用
    }

    return true; // 正常显示引用
  };

  return (
    <View
      style={[
        styles.messageContainer,
        isCurrentUser ? styles.containerRight : styles.containerLeft,
      ]}
    >
      {enableMultipleSelect && (
        <View style={styles.selectButton}>
          <RadioButton
            color="#3390ec"
            status={
              selectedMessages.includes(item.messageId)
                ? "checked"
                : "unchecked"
            }
            onPress={() => addSelectedMessage(item.messageId)}
            value={item.messageId}
          />
        </View>
      )}

      {/* 别人头像 */}
      {!isCurrentUser && (
        <TouchableHighlight
          underlayColor={"transparent"}
          style={styles.avatarContainer}
          onPress={() => onTouchAvatarPress(item.user.id)}
        >
          <Image source={{ uri: item.user.avatar }} style={styles.avatar} />
        </TouchableHighlight>
      )}

      {/*加载状态 / 失败警告*/}
      {isCurrentUser && item.status === MessageStatus.SENDING && (
        <View style={styles.messagestatus}>
          {showWarning ? (
            <TouchableOpacity onPress={handleRetry}>
              <MaterialIcons
                name="error"
                size={24}
                color="red"
                style={{ marginHorizontal: 4 }}
              />
            </TouchableOpacity>
          ) : (
            <ActivityIndicator size="small" color="#999" />
          )}
        </View>
      )}

      {/* 消息气泡 - 使用自定义长按菜单触发器 */}
      <View style={enableMultipleSelect && styles.messageSelectableContainer}>
        <TouchableOpacity
          activeOpacity={enableMultipleSelect ? 0.5 : 1}
          onPress={handleMessagePress}
          disabled={!enableMultipleSelect}
        >
          <MenuTrigger
            show={showMenu}
            setShow={setShowMenu}
            menus={getMenuItems()}
            onMenuItemPress={handleMenuItemPress}
            longPressDelay={500}
          >
            <View
              style={[
                styles.messageBubble,
                styles.messageBubbleStyle,
                isCurrentUser
                  ? [styles.bubbleRight, styles.bubbleRightStyle]
                  : [styles.bubbleLeft, styles.bubbleLeftStyle],
              ]}
            >
              {/* 如果有引用消息，先显示引用内容 */}
              {ensureQuoteContent() && (
                <View
                  style={{
                    width: "100%",
                    marginBottom: 4,
                  }}
                >
                  <ReplyContent
                    messageId={item.reply.replyMessageId}
                    username={item.reply.replyUserName}
                    content={quotePayload}
                    messageType={item.reply.replyMessageType}
                    revokeStatus={item.reply.replyRevokeStatus}
                  />
                </View>
              )}
              <Information />
            </View>
          </MenuTrigger>
        </TouchableOpacity>
      </View>

      {/* 当前用户头像 */}
      {isCurrentUser && (
        <TouchableHighlight
          underlayColor={"transparent"}
          style={styles.avatarContainer}
          onPress={() => onTouchAvatarPress(item.user.id)}
        >
          <Image source={{ uri: item.user.avatar }} style={styles.avatar} />
        </TouchableHighlight>
      )}
    </View>
  );
};

export default MessageItem;
